package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.exception.LogicalException;
import cn.wolfcode.wolf2w.query.StrategyThemeQueryObject;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import cn.wolfcode.wolf2w.util.PagingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
//@Transactional
public class StrategyThemeServiceImpl implements IStrategyThemeService {

    @Autowired
    private StrategyThemeRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public void save(StrategyTheme strategyTheme) {
        strategyTheme.setId(null);   //设为空值,防止数据库不会自动创建id
        repository.save(strategyTheme);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);

    }

    @Override
    public void update(StrategyTheme strategyTheme) {
        repository.save(strategyTheme);
    }

    @Override
    public StrategyTheme get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyTheme> list() {
        return repository.findAll();
    }

    @Override
    public Page<StrategyTheme> query(StrategyThemeQueryObject qo) {

        //查询封装类
        Query query = new Query();

        //查询分页
         Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        //调用工具方法,返回分页数据
        return PagingUtil.query(query, template, StrategyTheme.class, pageable);

    }

    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {
        //判断是否有id
        if (StringUtils.hasLength(strategyTheme.getId())){
            //这里是全量更新
            this.update(strategyTheme);
        }else {
            this.save(strategyTheme);
        }
    }


}
